import random

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.

# VIEW  APIVIEW  GENERICAPIVIEW  MIX.   VIEWSET
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from verifications import constants
from verifications import serializers
from verifications.utils.yuntongxun.sms import CCP
from .utils.captcha.captcha.captcha import captcha
import logging

logger = logging.getLogger("django")


class ImageCodeView(APIView):
    """
    图片验证码
    """

    def get(self, request, image_code_id):
        """
        获取图片验证码
        """
        # 生成验证码图片
        text, image = captcha.generate_captcha()
        # 拿前端传过来的标识作为key　　生成的图形验证码作为value
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 固定返回验证码图片数据，不需要REST framework框架的Response帮助我们决定返回响应数据的格式
        # 所以此处直接使用Django原生的HttpResponse即可
        # return Response(image, content_type="image/jpg")
        return HttpResponse(image, content_type="image/jpg")


# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
class SMSCodeView(GenericAPIView):
    """
    短信验证码
    """
    serializer_class = serializers.ImageCodeCheckSerializer

    def get(self, request, mobile):
        """
        创建短信验证码
        """
        # 判断图片验证码, 判断是否在60s内
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        # 000001
        # 保存短信验证码与发送记录
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 下面这个是对同一个手机号　不能多次请求发送短信　设置的短信间隔
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        # 发送短信验证码
        try:
            sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
            ccp = CCP()
            results = ccp.send_template_sms(mobile, [sms_code, sms_code_expires], 1)
        except Exception as e:
            logger.error("发送短信失败---->[%s]"%mobile)
            return Response({"message1":"发送短信失败"}, status=500)
        if results != 0:
            logger.error("发送短信失败---->[%s]" % mobile)
            return Response({"message2": "发送短信失败"}, status=500)

        return Response({"message": "OK"})